package com.oto.service;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import org.springframework.stereotype.Service;

import com.oto.model.AccountDO;
import com.oto.model.FlowDO;
import com.oto.web.model.XmlAccount;

/**
 * @author xueqiang.mi
 * @since 2010-12-18
 */
@Service
public class AccountService extends BaseService {

	public void add(AccountDO obj) {
		if (exist(obj.getName())) {
			return;
		}
		Date now = new Date();
		obj.setCrtDate(now);
		obj.setModDate(now);
		save(obj);
	}

	public AccountDO getOrCreate(String name, String type) {
		if (name == null) {
			return null;
		}
		AccountDO account = get(name);
		if (account == null) {
			account = new AccountDO();
			account.setName(name);
			account.setType(type);
			add(account);
		}
		return account;
	}

	public boolean addFriend(String userName, String fridName) {
		PersistenceManager pm = PMF.get();
		try {
			AccountDO account = pm.getObjectById(AccountDO.class, userName);
			if (account != null) {
				account.getFriends().add(fridName);
				return true;
			}
		} finally {
			pm.close();
		}
		return false;
	}

	public boolean exist(String name) {
		try {
			return (get(AccountDO.class, name) != null);
		} catch (Exception e) {
			// Ignore
			return false;
		}
	}

	public AccountDO get(String name) {
		try {
			return get(AccountDO.class, name);
		} catch (Exception e) {
			// Ignore
			return null;
		}
	}

	public List<AccountDO> list() {
		return list(AccountDO.class);
	}

	/**
	 * 将一个Flow直接推送给列表中的所有用户
	 * 
	 * @param toList
	 * @param flow
	 */
	public void pushFlow(List<XmlAccount> toList, FlowDO flow) {
		PersistenceManager pm = PMF.get();
		try {
			for (XmlAccount u : toList) {
				AccountDO account = null;
				try {
					account = pm.getObjectById(AccountDO.class, u.getName());
				} catch (Exception e) {
					// Ignore
				}
				if (account == null) {
					account = new AccountDO();
					account.setName(u.getName());
					account.setType(u.getType());
					Date now = new Date();
					account.setCrtDate(now);
					account.setModDate(now);
					account.getToQueue().add(flow.getId());
					pm.makePersistent(account);
				} else {
					account.getToQueue().add(flow.getId());
				}
			}
		} finally {
			pm.close();
		}
	}
}
